﻿using System;
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace QQZiFramework.MQ
{
    public static class Extension
    {
        /// <summary>
        /// 使用消息队列（要在DBContext.ServiceProvider赋值之前调用）
        /// </summary>
        public static void UserQQZiFrameworkMQ(this IServiceCollection services, IConfiguration configuration)
        {
            var configItem = configuration.GetSection("MessageQueue");
            if (configItem != null)
            {
                var typeName = configItem["Type"];
                if (!string.IsNullOrEmpty(typeName))
                {
                    Type t = Type.GetType(typeName);                    
                    if (t == null) throw new Exception("找不到类型" + typeName);
                    services.AddTransient(typeof(IMQDriver), t);
                    return;
                }
            }
            services.AddTransient(typeof(IMQDriver), typeof(RedisMQ));//如果没有指定，默认使用redis
        }


        public static IMQDriver GetMQDriver(this DBContext context)
        {
            // return DBContext.ServiceProvider.GetService(typeof(IMQDriver)) as IMQDriver;
            var mQDriver= context.GetArgument<IMQDriver>("IMQDRIVER");
            if(mQDriver ==null){
                mQDriver =  DBContext.ServiceProvider.GetService(typeof(IMQDriver)) as IMQDriver;
                context.SetArgument("IMQDRIVER",mQDriver);
            }
            return mQDriver;
        }
    }
}





// using System;
// using System.Reflection;
// using Microsoft.Extensions.Configuration;
// using Microsoft.Extensions.DependencyInjection;

// namespace QQZiFramework.MQ
// {
//     public static class Extension
//     {
//         /// <summary>
//         /// 使用消息队列（要在DBContext.ServiceProvider赋值之前调用）
//         /// </summary>
//         public static void UserQQZiFrameworkMQ(this IServiceCollection services, IConfiguration configuration)
//         {
//             var configItem = configuration.GetSection("MessageQueue");
//             if (configItem != null)
//             {
//                 var typeName = configItem["Type"];
//                 if (!string.IsNullOrEmpty(typeName))
//                 {
//                     Type t = Type.GetType(typeName);                    
//                     if (t == null) throw new Exception("找不到类型" + typeName);
//                     services.AddScoped(typeof(IMQDriver), t);
//                     return;
//                 }
//             }
//             services.AddScoped(typeof(IMQDriver), typeof(RedisMQ));//如果没有指定，默认使用redis
//         }


//         public static IMQDriver GetMQDriver(this DBContext context)
//         {
//             return  DBContext.ServiceProvider.GetService(typeof(IMQDriver)) as IMQDriver;
//         }


//     }
// }

